package com.praxinfosystems.sarthak.controllers;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.praxinfosystems.sarthak.common.AuthenticatedUserDetails;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping(value = "/", method = RequestMethod.GET)
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "homepage";
	}
	
	
	/**
	 * @Description : Authentication Failed Handler
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/authenticationFailed", method = RequestMethod.GET)
	public String authenticationFailed(Model model,HttpServletRequest request) {
		String errorMessage = "";
		 if(request.getParameter("error") != null && request.getParameter("error").equals("true")){
             errorMessage = "User Authentication Failed ";
             request.setAttribute("error", errorMessage);
      }
		 return "homepage";
	}
	
	/**
	 * 
	 * @param model
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/common", method = RequestMethod.GET)
	public String getDashboard(Model model, HttpServletRequest req) {
		String returnPage="error";
		AuthenticatedUserDetails user = (AuthenticatedUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Set<GrantedAuthority> roles=(Set<GrantedAuthority>) user.getAuthorities();
		String currentUserRole="";
		currentUserRole=roles.toString();
//		System.out.println("currentUserRole is "+currentUserRole);
		if(!currentUserRole.equals("")){
			if(currentUserRole.contains("ROLE_USER")){
				returnPage= "redirect:/subcontractor";
			}else if(currentUserRole.contains("ROLE_ADMIN")){
				returnPage= "redirect:/admindashboard";
			}
		}
		return returnPage;
	}
	
	@RequestMapping(value = "/admindashboard", method = RequestMethod.GET)
	public String getAdminDashBoard(Model model, HttpServletRequest req){
		return "admindashboard";
	}
	
}
